package com.chis.client;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

public class SignUtil {

    /**
     * 任意大小的数据，输出固定长度的哈希值
     * @param algorithm MD5,SHA-1
     * @param data
     * @return
     * @throws Exception
     */
    public static String createHashSign(String algorithm, byte[] data)throws Exception {
        byte[] ciphertext = MessageDigest.getInstance( algorithm).digest( data);
        return Hex.encodeHexString( ciphertext, false);
    }

    /**
     * MD系列的算法有HmacMD2、HmacMD4、HmacMD5三种算法；
     * SHA系列的算法有HmacSHA1、HmacSHA224、HmacSHA256、HmacSHA384.HmacSHA512五种算法
     * @param algorithm 加密算法
     * @param data 加密数据
     * @param secret 秘钥
     * @return
     * @throws Exception
     */
    public static String createHmacSign(String algorithm, byte[] data, byte[] secret)throws Exception {
        Mac hmac = Mac.getInstance( algorithm);
        SecretKeySpec secret_key = new SecretKeySpec( secret, algorithm);
        hmac.init(secret_key);
        byte[] array = hmac.doFinal( data);
        return Hex.encodeHexString( array, false);
    }

}
